package buckets.data;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import buckets.core.BucketsInstance;

/**
 * Utility tier for obtaining instances of bucket filling problem.
 * 
 * @author vasek
 *
 */
public final class BucketsInstanceContext implements InstanceContext {

	private static final String FILE_SEPARATOR = System.getProperty("file.separator");
	private static final String USER_DIR = System.getProperty("user.dir");
	private static final File INSTANCES = new File(USER_DIR + FILE_SEPARATOR + "resources" + FILE_SEPARATOR + "bucket" + FILE_SEPARATOR + "bu.inst.dat");
	private static final String DATA_SEPARATOR = " ";
	private static BucketsInstanceContext uniqueInstance;
	private final List<BucketsInstance> instances = new ArrayList<BucketsInstance>();
	
	/**
	 * Private constructor.
	 * 
	 * @throws IOException when a problem with a resource data file occurs
	 */
	private BucketsInstanceContext() throws IOException {
		final BufferedReader reader = new BufferedReader(new FileReader(INSTANCES));
		
		String line;
		while ((line = reader.readLine()) != null) {
			final String[] data = line.split(DATA_SEPARATOR);
			
			final int id = Integer.valueOf(data[0]);
			final int numberOfBuckets = Integer.valueOf(data[1]);
			final int[] capacities = new int[numberOfBuckets];
			final int[] originalCapacities = new int[numberOfBuckets];
			final int[] targetCapacities = new int[numberOfBuckets];
			final int offset = 2;
			
			for (int i = 0; i < numberOfBuckets; i++) {
				capacities[i] = Integer.valueOf(data[offset + i]);
				originalCapacities[i] = Integer.valueOf(data[offset + numberOfBuckets + i]);
				targetCapacities[i] = Integer.valueOf(data[offset + 2 * numberOfBuckets +  i]);
			}
			
			final BucketsInstance instance = new BucketsInstance(id, numberOfBuckets, capacities, originalCapacities, targetCapacities);
			instances.add(instance);
		}
	}
	
	@Override
	public List<BucketsInstance> getInstances() {
		return instances;
	}
	
	/**
	 * Access method for bucket filling problem instance context.
	 * 
	 * @return bucket instances context.
	 * @throws IOException when a problem with a resource data file occurs
	 */
	public static InstanceContext getContext() throws IOException {
		if (uniqueInstance == null) {
			uniqueInstance = new BucketsInstanceContext();
		}
		
		return uniqueInstance;
 	}

}
